package emd24.telstudyresources;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.json.*;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// Set button listeners
		
		Button btnStudy = (Button) this.findViewById(R.id.browse);
		btnStudy.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				begStudyMode();
			}
		});
		Button btnQuiz = (Button) this.findViewById(R.id.quiz);
		btnQuiz.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				begQuizCreate();
			}
		});
		Button btnProgress = (Button) this.findViewById(R.id.progress);
		btnProgress.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				begProgress();
			}
		});
		Button btnExit = (Button) this.findViewById(R.id.exit);
		btnExit.setOnClickListener(new OnClickListener() {
			public void onClick(View v){
				finish();
			}
		});
	}
	/**
	 * Starts the study mode activity to browse through questions.
	 * 
	 */
	private void begStudyMode(){
		Intent i = new Intent(this,StudyTableofContents.class);
		JSONLoader jl = new JSONLoader();
		ArrayList<BankHeader> head = null;
		jl.execute("https://mywebspace.wisc.edu/edyke/web/TELApp/header.txt");
		try {
			head = jl.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Check to see if there was a quiz error
		if(head == null){
			errorDatabase();
			return;
		}
		i.putParcelableArrayListExtra("header", head);
		startActivity(i);
	}
	/**
	 * Starts the quiz activity.
	 * 
	 */
	private void begQuizCreate(){
		Intent i = new Intent(this,QuizCreatorActivity.class);
		i.putExtra("mark", false);
		JSONLoader jl = new JSONLoader();
		ArrayList<BankHeader> head = null;
		jl.execute("https://mywebspace.wisc.edu/edyke/web/TELApp/header.txt");
		try {
			head = jl.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Check to see if there was a quiz error
		if(head == null){
			errorDatabase();
			return;
		}
		i.putParcelableArrayListExtra("header", head);
		startActivity(i);
	}
	/**
	 * Opens up the activity to show the users progress.
	 * 
	 */
	private void begProgress(){
		Intent i = new Intent(this,ProgressActivity.class);
		startActivity(i);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	/**
	 * Prints an error message if trouble opening the question database.
	 * 
	 */
	private void errorDatabase(){
		new AlertDialog.Builder(this).setMessage(R.string.database_error).
		setNeutralButton("Retry", new DialogInterface.OnClickListener() {
			// Set listener for when yes button is clicked, exit activity
			public void onClick(DialogInterface arg0, int arg1) {

			}
		}).show();
	}
	
	public static String getStringFromInputStream(InputStream is) {

		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();

		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	private class JSONLoader extends AsyncTask<String, Void, ArrayList<BankHeader>>{

		ProgressDialog d;
		int numQuestions;

		protected void onPreExecute() {
			super.onPreExecute();
			d = new ProgressDialog(MainActivity.this);
			d.setMessage("Loading...");
			d.setIndeterminate(false);
			d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			d.setCancelable(true);
			d.show();
		}
		protected ArrayList<BankHeader> doInBackground(String... params) {
			String parsedResult = null;
			try {
				// Get the JSON from online
				Log.e("QuizLoader"," QuizLoader: Starting Parse");
				URL url = new URL(params[0]);
				Log.e("QuizLoader"," QuizLoader: Starting Connection");
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				Log.e("QuizLoader"," QuizLoader:  Opening Connection");
				conn.connect(); //Open connection, code will fail here if there is no network connection
				InputStream is = conn.getInputStream();
				Log.e("QuizLoader"," QuizLoader:  Closing Connection");
				parsedResult = MainActivity.getStringFromInputStream(is);	
				is.close();
				return getBankHeaders(parsedResult);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		private ArrayList<BankHeader> getBankHeaders(String parsedResult) throws JSONException {
			JSONArray js = new JSONObject(parsedResult).getJSONArray("Banks");
			ArrayList<BankHeader> head = new ArrayList<BankHeader>();
			for(int i = 0; i < js.length(); i++){
				head.add(new BankHeader(js.getJSONObject(i)));
			}
			return head;
					
		}
		protected void onPostExecute(ArrayList<BankHeader> head){
			d.dismiss();
		}
	}
	

}
